<template>
  <div class="page-main"  v-title :data-title="dataTitle?dataTitle:'新建报工项目'">
    <home-nav :userData="userinfo"></home-nav>
    <div class="container">
      <div class="head-content">
        <span class="bold-font">创建报工项目</span>
        <div class="btn-line">
          <a-button v-if="checkPermission(['WORK_REPORT_MANAGER'])" class="hte-btn add-btn" type="primary"
            @click="handleSave">保存</a-button>
        </div>
      </div>
      <div class="content">
        <a-form-model ref="ruleForm" :model="project" :rules="rules">
          <section>
            <div class="section-header">基础信息</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="所属合同编号:" prop="contractNumber">
                  <a-input-search v-model="project.contractNumber" @search="showContractSelector = true"
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="所属合同名称:" prop="contractName">
                  <a-input v-model="project.contractName" placeholder="请输入合同名称"
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="采购订单号" prop="busKey">
                  <a-input v-model="project.busKey" placeholder="请输入采购订单号"
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同金额:" prop="amount">
                  <a-input v-model="project.amount" :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用号:" prop="costNumber">
                  <a-input v-model="project.costNumber" placeholder="请输入费用号"
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8"> </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="签订公司/代码:" prop="signCompanyCode">
                  <a-select
                    :value="project.signCompany && project.signCompanyCode ? project.signCompany + '/' + project.signCompanyCode : ''"
                    @change="(v) => changeSignCompanyCode(v)">
                    <a-select-option v-for="(item, index) in signCompany" :key="'companyName' + index"
                      :value="item.componyNo" :disabled="!checkPermission(['WORK_REPORT_MANAGER'])">
                      {{ item.componyName + '/' + item.componyNo }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="供应商/编码:" prop="supplierName">
                  <a-input-search :value="
                    (project.supplierName ? project.supplierName : '') +
                    '/' +
                    (project.supplierCode ? project.supplierCode : '')
                  " readOnly @change="changeSupplier" @search="showSupplierSelector = true"
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同签订人:" prop="signUser">
                  <UserInputSelector
                    :username.sync="project.signUserId"
                    :realname.sync="project.signUser"
                    multiple="multiple"
                    placeholder="请选择"
                  />   
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目负责人" prop="followPerson">
                  <UserInputSelector
                    :username.sync="project.followPersonId"
                    :realname.sync="project.followPerson"
                    multiple="multiple"
                    placeholder="请选择"
                  />   
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同跟进专员" prop="createOrderUser">
                  <UserInputSelector
                    :username.sync="project.createOrderUserId"
                    :realname.sync="project.createOrderUser"
                    multiple="multiple"
                    placeholder="请选择"
                  />  
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目经理" prop="proManager">
                  <UserInputSelector
                    :username.sync="project.proManagerId"
                    :realname.sync="project.proManager"
                    multiple="multiple"
                    placeholder="请选择"
                  />  
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目开始时间" prop="startTime">
                  <a-date-picker style="width: 100%" valueFormat="YYYY-MM-DD" v-model="project.startTime" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目结束时间" prop="endTime">
                  <a-date-picker v-model="project.endTime" style="width: 100%" valueFormat="YYYY-MM-DD" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8"> </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="是否数字贷：">
                  <a-radio-group name="radioGroup" v-model="project.digitalLoan">
                    <a-radio v-for="(code, index) in yesOrNot" :key="index" :value="code.code">
                      {{ code.name }}
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="备案证名称：">
                  <!-- <a-select>
              <a-select-option v-for="(item,index) in codes['数字贷备案证名称']" :key="index" :value="item.name">{{item.name}}</a-select-option>
            </a-select> -->
                  <a-select v-model="project.filingName">
                    <a-select-option v-for="(item, index) in codes['数字贷备案证名称']" :key="'filingName' + index"
                      :value="item.name" :disabled="!checkPermission(['WORK_REPORT_MANAGER'])">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <section>
            <div class="section-header">报工任务</div>
            <a-button @click="addTask()"> 增加 </a-button>
            <a-button @click="removeTask()"> 移除 </a-button>
            <a-table :scroll="{ x: 1800 }" class="hte-table-content" :columns="columns" :data-source="tasks"
              :pagination="false" :loading="tabLoading" rowKey="randomStr"
              :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" size="middle" bordered
              :customRow="customRow">
              <span slot="sortRender" slot-scope="text, record, index">
                {{ index + 1 }}
              </span>
              <span slot="purchaseOrderNumberRender" slot-scope="text, record">
                <span class="font-active" @click="toEditTask(record)">
                  {{ project.busKey + '(' + record.itemIndex + '/' + project.itemCount + ')' }}</span>
              </span>
              <span slot="complateTimeRender" slot-scope="text, record">
                {{ formatDate(record.complateTime || '', 'yyyy-MM-dd') }}
              </span>
              <span slot="planTimeRender" slot-scope="text, record">
                {{ formatDate(record.partaPlanTime || '', 'yyyy-MM-dd') }}
              </span>
              <span slot="actualTimeRender" slot-scope="text, record">
                {{ formatDate(record.partaActualTime || '', 'yyyy-MM-dd') }}
              </span>
              <template slot="isMutiContiditonRender" slot-scope="text, record">
                <template v-for="(code, index) in codes.IsMutiContiditon">
                  <span :key="index" v-if="record.isMutiContiditon == code.code">{{ code.name }}</span>
                </template>
              </template>
              <template slot="isPayNodeRender" slot-scope="text, record">
                <template v-for="(code, index) in codes.IsPayNode">
                  <span :key="index" v-if="record.isPayNode == code.code">{{ code.name }}</span>
                </template>
              </template>
              <template slot="statusRender" slot-scope="text, record">
                <span v-for="(code, index) in codes.WorkReportTaskStatus" :key="index">
                  <i v-if="record.status == code.code">{{ code.name }}</i>
                </span>
              </template>
              <template slot="paymentStatusRender" slot-scope="text, record">
                <span v-if="record.executeStatus == '5'">
                  <i>HIP已完成</i>
                </span>
                <span v-else v-for="(code, index) in codes.WorkReportTaskAcceptStatus" :key="index">
                  <i v-if="record.acceptStatus == code.code">{{ code.name }}</i>
                </span>
              </template>

              <template slot="nodeStatusRender" slot-scope="text, record">
                <span v-for="(code, index) in codes.WorkReportTaskStatus" :key="index">
                  <i v-if="record.partastatus == code.code">{{ code.name }}</i>
                </span>
              </template>
              <template slot="delayReasonRender" slot-scope="text, record">
                <span v-for="(code, index) in codes.WorkReportDelayReson" :key="index">
                  <i v-if="record.partaDelayReason == code.code">{{ code.name }}</i>
                </span>
              </template>
              <template slot="nodeStatusRender" slot-scope="text, record">
                {{ record.partaNodeStatus }}
              </template>

              <template slot="nodeContentRender" slot-scope="text, record">
                <span :class="'contentStyle-' + calcDelayType(record)">
                  {{ text }}
                </span>
              </template>
              <template slot="paymentContentRender" slot-scope="text, record">
                <span :class="'contentStyle-' + calcDelayType(record)">
                  {{ text }}
                </span>
              </template>
              <template slot="contractNameRender">
                {{ project.contractName }}
              </template>
              <template slot="amountRender">
                {{ project.amount }}
              </template>
              <template slot="contractNumberRender">
                {{ project.contractNumber }}
              </template>
            </a-table>
          </section>
          <section>
            <div class="section-header">报工附件</div>
            <a-button @click="handleDownload()"> 下载 </a-button>
            <a-button @click="removeAttach()"> 移除 </a-button>
            <a-button v-for="(key, index) in attachKeys" :key="index" @click="changeAttachKey(key)"
              :style="attachKey == key ? 'border-color: #40a9ff;' : ''">{{ index == 0 ? '主合同' : '补充协议' + index }}
            </a-button>
            <a-table :scroll="{ x: 1800 }" class="hte-table-content" :columns="attachColumns"
              :data-source="attachsFilter" :pagination="false" :loading="tabLoading" rowKey="randomStr"
              :row-selection="{ selectedRowKeys: selectedAttachKeys, onChange: onSelectAttachChange }" size="middle"
              bordered :customRow="customAttachRow">
              <template slot="previewRender1" slot-scope="text, record">
                <span class="font-active" @click="handlePreview(record)">
                  {{ record.fileName ? record.fileName : record.bidFile.fileName + '.' + record.bidFile.fileType }}
                </span>
              </template>
            </a-table>
          </section>
        </a-form-model>
      </div>
    </div>
    <a-modal title="请确认" :visible="showComfirm" @ok="handlerComfirm" @cancel="showComfirm = false" width="500px"
      :maskClosable="false">
      {{ tips }}
    </a-modal>
    <SupplierSelector :show="showSupplierSelector" @close="selectSupplier" />
    <ContractSelector :show="showContractSelector" @close="selectContract" />
    <TaskAdd :show="showEditTask" :project="project" :task="currentTask" @close="closeEditTask" />
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { formatFileSize, endWith } from '@/utils/common.js'
import { getAction, postAction, postActionAsync } from '@/api/manage'
import SupplierSelector from '@/views/workReport/util/SupplierSelector'
import ContractSelector from '@/views/workReport/util/ContractSelector'
import { formatDate } from '@/utils/util'
export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    TaskAdd: () => import('@/views/workReport/task/TaskAdd'),
    SupplierSelector,
    ContractSelector,
  },
  data() {
    return {
      dataTitle:this.$route?this.$route.name:"",
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      urls: {
        projectEdit: '/workReport/project/edit',
        projectSave: '/workReport/project/save',
        getProjectByBusKey: '/workReport/project/getProjectByBusKey',
        project: '/workReport/project/info',
        myPermission: '/workReport/project/myPermission',
        personList: '/person/info/personList',
        codes: '/manage/codeInfo/queryByTypes',
        loadSignCompany: '/hte/contract/loadSignCompany',
        getWorkReportByContract: '/workReport/project/getWorkReportByContract',
      },
      rules: {
        contractName: [{ required: true, message: '请输入', trigger: 'blur' }],
        contractNumber: [{ required: true, message: '请选择', trigger: 'blur' }],
        busKey: [{ required: true, message: '请输入', trigger: 'blur' }],
        amount: [{ required: true, message: '请输入', trigger: 'blur' }],
        costNumber: [{ required: true, message: '请输入', trigger: 'blur' }],
        signCompany: [{ required: true, message: '请选择', trigger: 'blur' }],
        supplierName: [{ required: true, message: '请选择', trigger: 'blur' }],
        proManager: [{ required: true, message: '请选择', trigger: 'blur' }],
        startTime: [{ required: true, message: '请选择', trigger: 'blur' }],
        endTime: [{ required: true, message: '请选择', trigger: 'blur' }],
        followPerson: [{ required: true, message: '请选择', trigger: 'blur' }],
        createOrderUser: [{ required: true, message: '请选择', trigger: 'blur' }],
        signUser: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      project: {},
      permission: [],
      personList: [],
      personMap: {},
      existPersonMap: {},
      codes: {},
      signCompany: [],
      showSupplierSelector: false,
      showContractSelector: false,
      showComfirm: false,
      tips: '',
      tasks: [],
      columns: [
        {
          title: '序号',
          align: 'center',
          width: '70px',
          scopedSlots: { customRender: 'sortRender' },
        },
        {
          title: '任务状态',
          dataIndex: 'status',
          align: 'center',
          scopedSlots: { customRender: 'statusRender' },
          width: '130px',
          ellipsis: true,
        },
        {
          title: '发起验收',
          dataIndex: 'paymentStatus',
          align: 'center',
          scopedSlots: { customRender: 'paymentStatusRender' },
          width: '130px',
          ellipsis: true,
        },
        {
          title: '报工单编号',
          dataIndex: 'itemIndex',
          align: 'center',
          sorter: true,
          scopedSlots: { customRender: 'purchaseOrderNumberRender' },
          width: '160px',
          ellipsis: true,
        },
        {
          title: 'PO单行号',
          dataIndex: 'poLine',
          align: 'center',
          width: '80px',
          ellipsis: true,
        },
        {
          title: '合同名称',
          dataIndex: 'contractName',
          scopedSlots: { customRender: 'contractNameRender' },
          align: 'center',
          width: '140px',
          ellipsis: true,
        },
        {
          title: '工期节点内容',
          dataIndex: 'nodeContent',
          align: 'center',
          width: '140px',
          ellipsis: true,
          scopedSlots: { customRender: 'nodeContentRender' },
        },
        {
          title: '项目负责人',
          dataIndex: 'handlerUser',
          align: 'center',
          width: '90px',
          ellipsis: true,
        },
        {
          title: '合同约定日期',
          dataIndex: 'complateTime',
          align: 'center',
          scopedSlots: { customRender: 'complateTimeRender' },
          width: '100px',
          ellipsis: true,
        },
        {
          title: '实际完成日期',
          dataIndex: 'actualTime',
          align: 'center',
          scopedSlots: { customRender: 'actualTimeRender' },
          width: '100px',
          ellipsis: true,
        },
        {
          title: '预计完成日期',
          dataIndex: 'planTime',
          align: 'center',
          scopedSlots: { customRender: 'planTimeRender' },
          width: '100px',
          ellipsis: true,
        },
        {
          title: '是否逾期',
          dataIndex: 'nodeStatus',
          scopedSlots: { customRender: 'nodeStatusRender' },
          align: 'center',
          width: '80px',
          ellipsis: true,
        },
        {
          title: '逾期责任方',
          dataIndex: 'delayReason',
          align: 'center',
          width: '90px',
          ellipsis: true,
          scopedSlots: { customRender: 'delayReasonRender' },
        },
        {
          title: '付款节点内容',
          dataIndex: 'paymentContent',
          align: 'center',
          width: 'left',
          width: '140px',
          ellipsis: true,
          scopedSlots: { customRender: 'paymentContentRender' },
        },
        {
          title: '付款节点',
          dataIndex: 'isPayNode',
          align: 'center',
          scopedSlots: { customRender: 'isPayNodeRender' },
          width: '75px',
          ellipsis: true,
        },
        {
          title: '多个付款节点',
          dataIndex: 'isMutiContiditon',
          align: 'center',
          scopedSlots: { customRender: 'isMutiContiditonRender' },
          width: '100px',
          ellipsis: true,
        },
        {
          title: '合同金额',
          dataIndex: 'amount',
          align: 'center',
          width: '80px',
          ellipsis: true,
          scopedSlots: { customRender: 'amountRender' },
        },
        {
          title: '关联节点金额',
          dataIndex: 'paymentAmount',
          align: 'center',
          width: '100px',
          ellipsis: true,
        },
        {
          title: '费用号',
          dataIndex: 'costNumber',
          align: 'center',
          width: '120px',
          ellipsis: true,
        },
        {
          title: '合同编号',
          dataIndex: 'contractNumber',
          align: 'center',
          width: '130px',
          ellipsis: true,
          scopedSlots: { customRender: 'contractNumberRender' },
        },
        {
          title: '节点标识',
          dataIndex: 'nodeIdentify',
          width: '22%',
          align: 'center',
          width: '80px',
          ellipsis: true,
        },
      ],
      selectedRowKeys: [],
      selectedRow: [],
      tabLoading: false,
      selectedAttachKeys: [],
      selectedAttachRow: [],
      attachs: [],
      attachColumns: [
        // {
        //   title: '所属附件名称',
        //   dataIndex: 'formName',
        //   key: 'formName',
        // },
        {
          title: '文件名称',
          dataIndex: 'fileName',
          key: 'fileName',
          scopedSlots: { customRender: 'previewRender1' },
        },
        {
          title: '上传人',
          dataIndex: 'createUser',
          key: 'createUser',
        },
        ,
        {
          title: '上传时间',
          dataIndex: 'createTime',
          key: 'createTime',
        },
      ],
      contract: {},
      currentTask: {},
      showEditTask: false,
      attachKey: '',
      attachKeys: [],
      attachsFilter: [],
      selectUserKeyWord: null,
      selectUserTimeOut: null,
      yesOrNot: [{ code: false, name: "否" }, { code: true, name: "是" }],
    }
  },
  async mounted() {
    this.fetchSignCompany()
    await this.fetchCodes()
    this.fetchPermission()
  },
  methods: {
    formatDate,
    fetchCodes() {
      let types = []
      types.push('QualityFineMethod')
      types.push('WorkReportTaskStatus')
      types.push('IsPayNode')
      types.push('IsMutiContiditon')
      types.push('WorkReportDelayReson')
      types.push('WorkReportTaskAcceptStatus')
      types.push('数字贷备案证名称')
      getAction(this.urls.codes, { types: types.join(',') }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
        }
      })
    },
    async fetchProjectByBusKey(busKey) {
      let res = await getAction(this.urls.getProjectByBusKey, { busKey })
      if (res.success) {
        if (!res.result) {
          return false
        } else {
          this.tips = '系统已存在采购订单号对应的报工项目，将会沿用'
          this.showComfirm = true
          this.project = res.result
          return true
        }
      }
    },
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.tasks) {
            let i = 0
            for (let task of this.tasks) {
              i++
              if (task.partaStatus == '2' && !task.partaActualTime) {
                return this.$messageWorkReport.warning('请输入序号为【' + i + '】实际完成时间')
              }
              if (!task.partaStatus && task.partaActualTime) {
                return this.$messageWorkReport.warning('请选择序号为【' + i + '】节点报工完成情况')
              }
              if (task.partaResult == '质量合格' && !task.partaAcceptTime) {
                return this.$messageWorkReport.warning('请输入序号为【' + i + '】现场验收时间')
              }
              if (!task.partaResult && task.partaAcceptTime) {
                return this.$messageWorkReport.warning('请选择序号为【' + i + '】节点报工质量情况')
              }
              if(task.partaStatus!=2 && task.partaResult != '质量合格' && task.partaNodeStatus == '逾期'){
                if(!task.partaPlanTime){
                  return this.$messageWorkReport.warning('逾期不完成且质量合格，请输入序号为【' + i + '】计划完成时间')
                }
              }
              if (task.partaStatus != '2') {
                if (task.partaNodeStatus == '逾期') {
                  if (!task.partaPlanTime || !task.partaDelayReason || !task.partaDelayRemark) {
                    return this.$messageWorkReport.warning(
                      '当【工期状态】=逾期，序号为【' + i + '】需要填写【预计完成日期】、【逾期责任方】、【逾期具体原因】'
                    )
                  }
                }
                if (task.partaPlanTime && (!task.partaDelayReason || !task.partaDelayRemark)) {
                  return this.$messageWorkReport.warning(
                    '当【工期状态】=逾期，序号为【' + i + '】需要填写【预计完成日期】、【逾期责任方】、【逾期具体原因】'
                  )
                }
              }
              let resultAttachs = task.partaAttachs
              if (task.partaStatus == '2' && task.partaResult == '质量合格') {
                task.partaIsCancleSubmit = '1'
              }
              if (!task.complateTime) {
                return this.$messageWorkReport.warning('请输入序号为【' + i + '】合同约定时间')
              }
              if (task.partaStatus == '1') {
                if (task.partaNodeStatus == '逾期') {
                  if (!task.partaPlanTime) {
                    return this.$messageWorkReport.warning('请填写序号为【' + i + '】预计完成日期')
                  }
                  if (!task.partaDelayReason) {
                    return this.$messageWorkReport.warning('请选择序号为【' + i + '】逾期责任方')
                  }
                  if (!task.partaDelayRemark) {
                    return this.$messageWorkReport.warning('请选择序号为【' + i + '】逾期具体原因')
                  }
                }
                if (task.partaResult == '质量合格') {
                  return this.$messageWorkReport.warning('序号为【' + i + '】请勿选择[质量合格]')
                }
              }
              if (task.partaStatus == '2') {
                if (!task.partaActualTime) {
                  return this.$messageWorkReport.warning('请填写序号为【' + i + '】实际完成时间')
                }
                if (task.partaNodeStatus == '逾期') {
                  if (!task.partaDelayReason) {
                    return this.$messageWorkReport.warning('请选择序号为【' + i + '】逾期责任方')
                  }
                  if (!task.partaDelayRemark) {
                    return this.$messageWorkReport.warning('请选择序号为【' + i + '】逾期具体原因')
                  }
                }
              }
              if (task.partaResult == '质量合格') {
                if (!task.partaAcceptTime) {
                  return this.$messageWorkReport.warning('请输入序号为【' + i + '】现场验收时间')
                } else {
                  var acceptTime = new Date(task.partaAcceptTime).getTime()
                  var actualTime = new Date(task.partaActualTime).getTime()
                  if (acceptTime < actualTime) {
                    return this.$messageWorkReport.warning('序号为【' + i + '】现场验收时间必须晚于或等于实际完成时间')
                  }
                }
                if (task.nodeIdentify == '验收' || task.isPayNode == '1') {
                  if (resultAttachs) {
                    let hasAcceptFile = false
                    resultAttachs.forEach((attach) => {
                      if (attach.fileName && attach.fileName.indexOf('验收') > -1) {
                        hasAcceptFile = true
                      }
                    })
                    if (!hasAcceptFile) {
                      return this.$messageWorkReport.warning('请上传【' + i + '】验收单附件')
                    }
                  } else {
                    return this.$messageWorkReport.warning('请上传【' + i + '】验收单附件')
                  }
                }
              }
            }
          }
          if (this.signCompany) {
            let isCorrect = false
            this.signCompany.forEach((c) => {
              if (c.componyNo == this.project.signCompanyCode && c.componyName == this.project.signCompany) {
                isCorrect = true
              }
            })
            if (!isCorrect) {
              return this.$messageWorkReport.warning(
                '当前签订公司[' +
                this.project.signCompany +
                '/' +
                this.project.signCompanyCode +
                ']不正确，请[合同报工管理员]在合同页面进行修正'
              )
            }
          }
          this.$set(this.project, 'tasks', this.tasks)
          this.$set(this.project, 'attachs', this.attachs)
          this.$set(this.project, 'contract', this.contract)
          let url = this.$route.path.startsWith('/workReport/addProject')
            ? this.urls.projectSave
            : this.urls.projectEdit
          postAction(url, this.project).then((res) => {
            if (res.success) {
              this.project = res.result
              this.$messageWorkReport.success('保存成功')
              if (this.$route.path.startsWith('/workReport/addProject')) {
                let urlJump = this.$router.resolve({ path:'/workReport/taskList?projectId=' + this.project.id })
                window.open(urlJump.href, '_blank')
                window.close()
              } else {
                this.$router.go(0)
              }
            } else {
              this.$messageWorkReport.error(res.message)
            }
          })
        }
      })
    },
    clickPersonSelector(type, mutil) {
      this.currentType = type
      this.mutil = mutil
      let usernames = this.project[type + 'Id'] ? this.project[type + 'Id'].split(',') : []
      let realnames = this.project[type] ? this.project[type].split(',') : []
      for (let i = 0; i < realnames.length; i++) {
        this.$set(this.existPersonMap, realnames[i], usernames[i])
      }
    },
    fetchPermission() {
      getAction(this.urls.myPermission, { projectId: '-1' }).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = true
      // for (let p of powers) {
      //   if (this.permission.indexOf(p) > -1) {
      //     hasPower = true
      //     break
      //   }
      // }
      return hasPower
    },
    fetchSignCompany() {
      getAction(this.urls.loadSignCompany, {}).then((res) => {
        if (res.code == 200) {
          this.signCompany = res.result
        } else {
          this.$messageWorkReport.warning('请求数据失败:' + res.msg)
        }
      })
    },
    selectSupplier(supplier) {
      if (supplier) {
        this.$set(this.project, 'supplierName', supplier.sp_name)
        this.$set(this.project, 'supplierCode', supplier.sp_no)
      } else {
        this.$set(this.project, 'supplierName', '')
        this.$set(this.project, 'supplierCode', '')
      }
      this.showSupplierSelector = false
    },
    async selectContract(contract, filterByContract) {
      if (contract) {
        let params = Object.assign({}, contract)
        params.filterByContract = filterByContract + ''
        let workReportRes = await postAction(this.urls.getWorkReportByContract, params)
        if (workReportRes.success) {
          let workReport = workReportRes.result
          this.project = workReport.project
          this.tasks = workReport.tasks
          this.attachs = workReport.attachs
          this.attachKeys = workReport.attachKeys
          if (this.attachKeys && this.attachKeys.length > 0) {
            this.attachKey = this.attachKeys[0]
          }
          this.changeAttachKey(this.attachKey)
          this.randomString(10)
          this.contract = workReport.contract
          this.tasks.forEach((t) => {
            t.status = this.calcTaskStatus(t.partaResult, t.partbResult)
          })
        } else {
          this.$messageWorkReport.error(workReportRes.message)
        }
      }
      this.showContractSelector = false
    },
    changeAttachKey(attachKey) {
      this.attachKey = attachKey
      let attachsFilterTemp = []
      if (this.attachs && this.attachs.length > 0) {
        this.attachs.forEach((a) => {
          if (a.busKey == this.attachKey) {
            attachsFilterTemp.push(a)
          }
        })
      }
      this.attachsFilter = attachsFilterTemp
    },
    changeSupplier() {
      if (!this.project.supplierName || !this.project.supplierCode) {
        this.$set(this.project, 'supplierName', '')
        this.$set(this.project, 'supplierCode', '')
      }
    },
    handlerComfirm() {
      this.showComfirm = false
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    customRow(record) {
      return {
        on: {
          dblclick: (event) => {
            this.currentTask = record
            this.showEditTask = true
          },
        },
      }
    },
    toEditTask(record) {
      this.currentTask = record
      this.showEditTask = true
    },
    closeEditTask(newTask) {
      if (newTask) {
        let newTasks = []
        for (let t of this.tasks) {
          if (t.randomStr == newTask.randomStr) {
            newTasks.push(newTask)
          } else {
            newTasks.push(t)
          }
        }
        this.tasks = newTasks
        console.info(newTasks)
        console.info(this.tasks)
      }
      this.showEditTask = false
    },
    onSelectAttachChange(selectedRowKeys, selectedRow) {
      this.selectedAttachKeys = selectedRowKeys
      this.selectedAttachRow = selectedRow
    },
    customAttachRow(record) {
      return {
        on: {
          dblclick: (event) => {
            this.handlePreview(record)
          },
        },
      }
    },
    handleDownload() {
      if (this.selectedAttachRow.length == 1) {
        let record = this.selectedAttachRow[0]
        if (record.busFk) {
          const token = Vue.ls.get(ACCESS_TOKEN)
          let url =
            process.env.VUE_APP_API_BASE_URL + '/workReport/attach/download?token=' + token + '&id=' + record.busFk
          if (record.platForm == 'CLOUD') {
            url =
              process.env.VUE_APP_PS_API_BASE_URL +
              '/hte/contract/downloadUnion?&id=' +
              record.busFk +
              '&platForm=CLOUD' +
              '&fileName=' +
              record.fileName
          }
          if (record.platForm == 'CLOUDFOLDER') {
            url =
              process.env.VUE_APP_PS_API_BASE_URL +
              '/hte/contract/downloadUnion&id=' +
              record.busFk +
              '&platForm=CLOUDFOLDER' +
              '&fileName=' +
              record.fileName
          }
          window.open(url)
        }
      } else if (this.currentSelection.length > 1) {
        let newIds = []
        this.currentSelection.forEach((r) => {
          newIds.push(r.busFk + '_' + r.platForm + '_' + r.fileName)
        })
        const token = Vue.ls.get(ACCESS_TOKEN)
        let url =
          process.env.VUE_APP_API_BASE_URL +
          '/workReport/attach/downloadUnionZip?token=' +
          token +
          '&ids=' +
          newIds.join(',')
        window.open(url)
      }
    },
    handlePreview(file) {
      let that = this
      if (
        endWith(file.fileName, 'rar') ||
        endWith(file.fileName, 'zip') ||
        endWith(file.fileName, 'dwg') ||
        endWith(file.fileName, 'tgz')
      ) {
        return true
      }
      let token = Vue.ls.get(ACCESS_TOKEN)
      let url =
        process.env.VUE_APP_API_BASE_URL + '/common/previewAttach?token=' + token + '&id=' + file.busFk + '&ftpKey=ftp'
      if (file.platForm == 'CLOUD') {
        url =
          process.env.VUE_APP_PS_API_BASE_URL +
          '/hte/contract/previewAttachUnion?id=' +
          file.busFk +
          '&ftpKey=ftp' +
          '&fileName=' +
          file.fileName +
          '&platForm=' +
          file.platForm
      }
      if (file.platForm == 'CLOUDFOLDER') {
        url =
          process.env.VUE_APP_PS_API_BASE_URL +
          '/hte/contract/previewAttachUnion?id=' +
          file.busFk +
          '&ftpKey=ftp' +
          '&fileName=' +
          file.fileName +
          '&platForm=' +
          file.platForm
      }
      console.info(url)
      window.open(process.env.BASE_URL + '/pdf/web/viewer.html?file=' + encodeURIComponent(url))
    },
    calcDelayType(record) {
      let _now = new Date()
      let complateTime = new Date(record.complateTime)
      if (!record.resultStatus || record.resultStatus == '0') {
        if (_now >= complateTime) {
          return 'red'
        }
        let expire = complateTime - _now
        if (expire <= 7 * 24 * 60 * 60 * 1000) {
          return 'yellow'
        }
      }
      if (record.resultStatus == '1') {
        let planTime = new Date(record.planTime)
        if (_now >= planTime) {
          return 'red'
        }
        let expire = planTime - _now
        if (expire <= 7 * 24 * 60 * 60 * 1000) {
          return 'yellow'
        }
      }
      return 'default'
    },
    randomString(len) {
      if (this.tasks) {
        this.tasks.forEach((t) => {
          t.randomStr = this.getRandomStr(len)
        })
        this.attachs.forEach((t) => {
          t.randomStr = this.getRandomStr(len)
        })
      }
    },
    addTask() {
      let task = {}
      task.randomStr = this.getRandomStr(10)
      task.itemIndex = this.tasks.length + 1
      this.tasks.push(task)
      this.currentTask = task
      this.$set(this.project, 'itemCount', this.tasks.length)
      this.showEditTask = true
    },
    getRandomStr(len) {
      len = len || 32
      var $chars =
        'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    removeTask() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length <= 0) {
        this.$messageWorkReport.warning('请至少选择一个记录进行操作')
        return false
      } else {
        let newList = []
        this.tasks.forEach((t) => {
          if (!(this.selectedRowKeys.indexOf(t.randomStr) > -1)) {
            newList.push(t)
          }
        })
        this.tasks = newList
        this.selectedRowKeys = []
        this.selectedRow = []
      }
    },
    removeAttach() {
      if (!this.selectedAttachKeys || this.selectedAttachKeys.length <= 0) {
        this.$messageWorkReport.warning('请至少选择一个记录进行操作')
        return false
      } else {
        let newList = []
        this.attachs.forEach((t) => {
          if (!(this.selectedAttachKeys.indexOf(t.randomStr) > -1)) {
            newList.push(t)
          }
        })
        this.attachs = newList
        this.selectedAttachKeys = []
        this.selectedAttachRow = []
      }
      this.changeAttachKey(this.attachKey)
    },
    calcTaskStatus(resultA, resultB) {
      let taskResultMap = {}
      taskResultMap['0000'] = '0' //甲未报工，乙未报工
      taskResultMap['0010'] = '1' //甲未报工，乙报完成
      taskResultMap['0011'] = '2' //甲未报工，乙报合格
      taskResultMap['1000'] = '3' //甲报完成，乙未报工
      taskResultMap['1010'] = '4' //甲报完成，乙报完成
      taskResultMap['1011'] = '5' //甲报完成，乙报合格
      taskResultMap['1100'] = '6' //甲报合格，已未报工
      taskResultMap['1110'] = '7' //甲报合格，乙报完成
      taskResultMap['1111'] = '8' //甲报合格，乙报合格
      let resultMap = {}
      resultMap['质量不合格'] = '10'
      resultMap['质量合格'] = '11'
      let prefix = '00'
      let suffix = '00'
      if (resultMap[resultA]) {
        prefix = resultMap[resultA]
      }
      if (resultMap[resultB]) {
        suffix = resultMap.get(resultB)
      }
      let key = prefix + suffix
      let taskStatus = taskResultMap[key]
      return taskStatus
    },
    changeSignCompanyCode(v) {
      this.$set(this.project, 'signCompanyCode', v)

      if (this.project.signCompanyCode) {
        this.signCompany.forEach((s) => {
          if (s.componyNo == this.project.signCompanyCode) {
            this.project.signCompany = s.componyName
            this.$set(this.project, 'signCompany', s.componyName)
          }
        })
      } else {
        this.$set(this.project, 'signCompany', '')
      }
      console.info(this.project)
    },
  },
  watch: {},
}
</script>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.page-main {
  .container {
    .content {
      margin-top: 20px;

      section {
        margin-bottom: 18px;

        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }

          /deep/ .a-upload__input {
            display: none !important;
          }
        }
      }
    }
  }

  .tips-box {
    margin-top: 32px;

    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}

/deep/ .el-upload__input {
  display: none !important;
}
</style>

